window.mapsearch = (function() {
    var userCenter = {};

    var marker = new google.maps.Marker({
        map: lib.objectMap.map
    });

    var newmarker = new google.maps.Marker({
        map: lib.objectMap.map
    });        
        
    function createMarker(lat,lon,html,map) {
        newmarker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, lon),
            map: map.map,
            draggable: true,
            title: html,
            icon: '/css/images/map-icon.png'
        });
        if(map.markers.length == 0){
            map.marker_ini = newmarker;
        } 
        map.markers.push(newmarker);
        newmarker['infowindow'] = new google.maps.InfoWindow({content: html});
        google.maps.event.addListener(newmarker, 'click', function() {
            this['infowindow'].open(map.map, this);
            map.marker_delete = newmarker;
            map.map.setCenter(newmarker.getPosition());
        });
        
        google.maps.event.addListener(newmarker, 'dragend', function(event) {        
          var marker_position = newmarker.getPosition();
          lib.objectMap.map.panTo(new google.maps.LatLng(marker_position.lat(),marker_position.lng()));
          mapsearch.userCenter = {"lat":marker_position.lat(), "lon":marker_position.lng()};
        });        
    }
      
    function marker_setup(map){
        var i = 0;        
        if (typeof lib.place_object['place0'] != 'undefined')
          for(property in lib.place_object) {
              lat = lib.place_object["place" + i].latlon[0];
              lan = lib.place_object["place" + i].latlon[1];
              description = lib.place_object["place" + i].description;
              createMarker(lat,lan,description,map);
              i++;
          }   
    }
    
    function marker_delete(){
        lib.objectMap.marker_ini.setMap(null);
        if (lib.objectMap.marker_delete !== null) lib.objectMap.marker_delete.setMap(null);
    }    
      
    function initialize_edit(lat, lon) {
        mapsearch.userCenter = {"lat":lat, "lon":lon};
        lib.coords_start = [lat, lon];
        lib.place_object = {"place0":{"latlon":[lat, lon],"description":"Здесь я"}};                        
        lib.objectMap = {};
        lib.objectMap.map = null;
        lib.objectMap.markers = [];
        lib.objectMap.current_position = [];
        lib.objectMap.marker_delete = null;
        lib.objectMap.marker_ini = null;    
           
        var mapOptions = {
            center: new google.maps.LatLng(lib.coords_start[0],lib.coords_start[1]),
            zoom: 12,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
        };
        lib.objectMap.map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
        var input = document.getElementById('searchCityField');
        var options = {componentRestrictions: {country: 'ru'}};
        var autocomplete = new google.maps.places.Autocomplete(input,options);
        autocomplete.bindTo('bounds', lib.objectMap.map);
        
        if (typeof lib.place_object['place0'] == 'undefined')
          lib.objectMap.marker_ini = new google.maps.Marker({map: lib.objectMap.map});        
        
        /*google.maps.event.addListener(lib.objectMap.map,'click',function(event) {
            lib.objectMap.marker_ini.setMap(null);
            var marker_position = event.latLng;   
            lib.objectMap.marker_ini = new google.maps.Marker({
                map: lib.objectMap.map,
                draggable: true,
                icon: '/css/images/map-icon.png'
            });
            lib.objectMap.marker_ini.setPosition(marker_position);
            lib.objectMap.current_position = event.latLng;
            document.getElementById('position').value = event.latLng;
            //здесь плавно переместить центр карты          
            lib.objectMap.map.panTo(new google.maps.LatLng(event.latLng.lat(),event.latLng.lng()));

            google.maps.event.addListener(lib.objectMap.marker_ini, 'dragend', function(event) {
              var marker_position = lib.objectMap.marker_ini.getPosition();
              lib.objectMap.map.panTo(new google.maps.LatLng(marker_position.lat(),marker_position.lng()));
            });            
        });*/                                        
        
        var infowindow = new google.maps.InfoWindow();
        
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            infowindow.close();
            marker.setVisible(false);
            input.className = '';
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                input.className = 'notfound';
                return;
            }
            if (place.geometry.viewport) {
                lib.objectMap.map.fitBounds(place.geometry.viewport);
            } else {
                lib.objectMap.map.setCenter(place.geometry.location);
                lib.objectMap.map.setZoom(16);
            }
            
            lib.objectMap.marker_ini.setMap(null);
            var marker_position = place.geometry.location;   
            lib.objectMap.marker_ini = new google.maps.Marker({
                map: lib.objectMap.map,
                draggable: true,
                icon: '/css/images/map-icon.png'
            });
            lib.objectMap.marker_ini.setPosition(marker_position);
            lib.objectMap.current_position = marker_position;
            document.getElementById('position').value = marker_position;                      

            google.maps.event.addListener(lib.objectMap.marker_ini, 'dragend', function(event) {
              var marker_position = lib.objectMap.marker_ini.getPosition();
              lib.objectMap.map.panTo(new google.maps.LatLng(marker_position.lat(),marker_position.lng()));
            });
            
            mapsearch.userCenter = {"lat":marker_position.lat(), "lon":marker_position.lng()};          
            
            $('#selectorCityTarget span').text(place.address_components[0].short_name);
            $(".selector-city_target").click();
        });
        
        autocomplete.setTypes([]);
        marker_setup(lib.objectMap);
    }  
  
    var nav = null; 
    function successCallback(position) { 
      //удалось определить положение юзера
      initialize_edit(position.coords.latitude, position.coords.longitude);
    }
  
    function errorCallback(error) {
      //не удалось определить положение юзера. Эти координаты надо откуда-то брать из базы
      initialize_edit(56.320636625218356, 44.00299072265625);
    }            

    var requestPosition = function () {
        lib.searchMapDrown = true;
        if (nav == null) {nav = window.navigator;}
        
        var geoloc = nav.geolocation;
        if (geoloc != null) {
            geoloc.getCurrentPosition(successCallback, errorCallback);
        }
    }
    
		var drawGeoJSON = function(geojson, options){
			var myGoogleVector = new GeoJSON(geojson, options);

			if (myGoogleVector.error){
				alert('error');
			} else {
				myGoogleVector.setMap(lib.objectMap.map);
			}
		}    
    
  return {
      requestPosition: requestPosition,
      drawGeoJSON: drawGeoJSON,
      userCenter: userCenter,
      initialize_edit: initialize_edit      
  };
})(jQuery);
    